/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package de.blitzcoder.collide.gui;

import de.blitzcoder.collide.util.Log;
import groovy.lang.GroovyShell;
import groovy.ui.ConsoleTextEditor;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author blitzcoder
 */
public class GroovyShellDocument extends Document {

    private GroovyShell shell;
    private ConsoleTextEditor editor;
    private JButton evalButton;
    private JTextArea output;
    private static GroovyShellDocument instance = null;
    
    public static GroovyShellDocument getInstance() {
        if (instance == null)
            instance = new GroovyShellDocument();
        return instance;
    }
    
    private GroovyShellDocument() {}
    
    public void load() {
        shell = new GroovyShell();
        
        setLayout(new GridBagLayout());
        
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        
        evalButton = new JButton("Starten");
        editor = new ConsoleTextEditor();
        output = new JTextArea();
        output.setEditable(false);
        
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 0.0;
        c.weighty = 0.0;
        add(evalButton,c);
        
        c.gridy = 1;
        c.weightx = 1.0;
        c.weighty = 0.5;
        c.fill = c.BOTH;
        add(editor,c);
        
        c.gridy = 2;
        add(new JScrollPane(output),c);
        
        c.fill = c.BOTH;
        
        evalButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                runCode();
            }
        });

    }

    private void runCode() {

        String code = editor.getTextEditor().getText();
        String result = null;

        try {
            Object res = shell.evaluate(code);
            Log.log("Class: "+res.getClass().getName());
            if (res instanceof String)
                result = (String)res;
        } catch (Exception ex) {
            output.append("\n"+ex.getMessage());
            return;
        }

        if (result != null) {
            output.append(result);
        } else {
            output.append("No Result...\n");
        }

    }

    @Override
    public String getTitle() {
        return "Groovy Shell";
    }

    @Override
    public Icon getIcon() {
        return de.blitzcoder.collide.icons.Icon.load("file_text.png");
    }

    @Override
    public String getToolTip() {
        return "Groovy Shell";
    }

    @Override
    public boolean equalsFile(File file) {
        return false;
    }

}
